package com.ophiux.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ophiux.util.DateUtil;
import com.ophiux.util.PropertyUtil;

import net.coobird.thumbnailator.Thumbnails;


/**
 * 说明：前端上传图片到服务器<br>
 * <h1>创 建 人: hehailong<br></h1>
 * 创建日期: 2018年9月28日 下午3:21:16<br>
 * 修改记录：
 */
@Controller
@RequestMapping(value = "/upload")
public class ImgController {
	private final static String ENCODE = "UTF-8";

	private static Logger logger = LoggerFactory.getLogger(ImgController.class);

	@RequestMapping(value = "/uploadImg", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	@ResponseBody
	public String uploadImg(@RequestParam("file") MultipartFile file) {
		String imgPath = "";// 存入数据库图片路径
		try {
				if (!"image/jpeg".equals(file.getContentType()) && !"image/png".equals(file.getContentType())) {
					return "";
				}
				if(file.getSize()/1024>1024) {
					System.out.println(" file name = " + file.getOriginalFilename() + ", file size = " + file.getSize()/1024/1024 +"M");
				}else {
					System.out.println(" file name = " + file.getOriginalFilename() + ", file size = " + file.getSize()/1024 +"KB");
				}
				String newPath = keepUploadImg(file, "webp", "jpg");
				imgPath = imgPath + newPath;
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("上传图片异常",e);
			return "";
		}
		System.out.println(imgPath);
		return imgPath;
	}

	/**
	 * 保存图片到磁盘
	 * @param file
	 * @param zipFileType
	 * @param sourceFileType
	 * @return
	 */
	public String keepUploadImg(MultipartFile file,String zipFileType, String sourceFileType) throws Exception {
		String date = DateUtil.getCurrentDate("yyyyMMdd")+"/";
		String newFilePath = "";
		try {
			String filePath = PropertyUtil.getResValue("IMG_UPLOAD_URL")+ date;
			// 获取操作时间
			String dateString = DateUtil.getCurDateRandom();
			// 获取毫秒
			long t1 = System.currentTimeMillis();
			File dir = new File(filePath);
			if (!dir.exists())
				dir.mkdirs();
			// 文件夹--存放压缩之前的原文件
			File dirzip = new File(filePath + "/yuanjian");
			if (!dirzip.exists())
				dirzip.mkdirs();
			// 拼接唯一文件名
			String newFileName = dateString + t1;
			File tagetFile = new File(filePath + "/yuanjian/" + newFileName + "." + sourceFileType);// 创建文件对象
			FileOutputStream output = new FileOutputStream(filePath + "/" + newFileName + "." + zipFileType);
			if (!tagetFile.exists()) {// 文件名不存在 则新建文件，并将文件复制到新建文件中
				try {
					tagetFile.createNewFile();
					file.transferTo(tagetFile);
					
					Thumbnails.of(filePath + "/yuanjian/" + newFileName + "." + sourceFileType).scale(1).toOutputStream(output);
					output.flush();
					output.close();
					
					tagetFile.delete();//删除源文件
					
					newFilePath = filePath + newFileName + "." + zipFileType;
				} catch (Exception e) {
					output.flush();
					output.close();
					e.printStackTrace();
				}
			}
			return newFilePath;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

	/**
	 * 获取图片页面展示
	 * @param imgPath
	 */
	@RequestMapping(value = "/getImg")
	public void getImg(HttpServletRequest request, HttpServletResponse response,@RequestParam("imgPath") String imgPath) {
		String moWeiFilePath = getURLDecoderString(imgPath);
		String filePath = moWeiFilePath;
		FileInputStream inputStream = null;
		OutputStream out = null;
		try {
			inputStream = new FileInputStream(filePath);
			int i = inputStream.available();
			byte[] buff = new byte[i];
			inputStream.read(buff);
			inputStream.close();
			response.setContentType("image/*");
			out = response.getOutputStream();
			out.write(buff);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除图片
	 * @param imgPath
	 * @return
	 */
	@RequestMapping(value = "/deleteImg")
	public boolean doRmoeve(@RequestParam("imgPath") String imgPath) {
		String moWeiFilePath = getURLDecoderString(imgPath);
		String[] sourceFilePathS = moWeiFilePath.split("/");
		String sourceFilePath = sourceFilePathS[0];
		for (int i = 1; i < sourceFilePathS.length - 2; i++) {
			sourceFilePath = sourceFilePath + "/" + sourceFilePathS[i];
		}
		sourceFilePath = sourceFilePath + "/" + sourceFilePathS[sourceFilePathS.length - 1];
		File fileZip = new File(moWeiFilePath);
		File sourceFileZip = new File(sourceFilePath);
		try {
			if (fileZip.exists()) {
				if (fileZip.isFile()) {
					// 删除压缩文件
					fileZip.delete();
				}
			}
			if (sourceFileZip.exists()) {
				if (sourceFileZip.isFile()) {
					// 删除源文件
					sourceFileZip.delete();
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
	public static void main(String[] args) {
		System.out.println(getURLEncoderString("D:/HospitalPlatForm/tomcats/Tomcat_BA/ophiuxImg/20181211/201812111700261544518826060.webp"));
	}

	/**
	 * URL 转码
	 * 
	 * @return
	 */
	public static String getURLEncoderString(String str) {
		String result = "";
		if (null == str) {
			return "";
		}
		try {
			result = java.net.URLEncoder.encode(str, ENCODE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * URL 解码
	 */
	public static String getURLDecoderString(String str) {
		String result = "";
		if (null == str) {
			return "";
		}
		try {
			result = java.net.URLDecoder.decode(str, ENCODE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
